import { ref, watch, reactive } from 'vue';
import { getPerson } from '@/api/system/role';
import { defineStore } from 'pinia';
import { Person } from '@/types8';

export const usequanju = defineStore('quanju', () => {
  const conditions = reactive({
    role: 'all',
    state: 'all',
    department: 'all',
  });

  const limit = 5,
    page = ref(1),
    todos = ref<Person[]>([]),
    count = ref(0),
    maxPage = ref(1);
  // 查询
  const search = async () => {
    // 如果已经加载到最后一页，则放弃发起请求
    // if (isEnd.value) return;
    // 发起查询请求
    const data = await getPerson({
      ...conditions,
      offset: (page.value - 1) * limit,
      limit,
    });
    // console.log(data);
    if (data) {
      count.value = data.count;
      page.value = data.page;
      // 计算最大分页数
      maxPage.value = Math.ceil(count.value / limit);

      todos.value = data.result;
      // console.log(todos);
    }
  };
  watch(page, () => {
    search();
  });
  watch(
    conditions,
    () => {
      todos.value = [];
      page.value = 1;
      search();
    },
    { deep: true }
  );
  // 使用特殊环境变量替代 baseURL

  return {
    search,
    limit,
    page,
    conditions,
    count,
    todos,
    maxPage,
  };
});
